import io from '@hyoga/uni-socket.io'
import store from '@/store/index.js'

class SocketManager {
	constructor() {
		this.socket = null
	}

	// 初始化
	initialize(userId) {
		if (this.socket === null) {
			this.socket = io('ws://192.168.101.163:5001', {
				query: { userId },
				transports: ['websocket', 'polling'],
				timeout: 5000,
			})

			// 连接
			this.socket.on('connect', () => {
				console.log('连接成功')
				this.socket.emit('chatData')
			})

			// 初始化信息
			this.socket.on('chatData', res => {
				store.dispatch('handleChatData', res.data)
			})

			// 添加好友
			this.socket.on('addFriend', res => {
				console.log('添加好友')
			})

			// 建立聊天
			this.socket.on('joinFriendSocket', res => {
				console.log('建立私聊')
			})

			// 系统通知
			this.socket.on('notice', res => {
				console.log('系统通知', res)
				store.commit('ADD_NOTICE_MESSAGE', res.data)
			})
			
			// 投递简历
			this.socket.on('delivery', res => {
				console.log('投递简历', res)
				store.commit('ADD_NOTICE_MESSAGE', res.data)
			})
			
			// 面试预约
			this.socket.on('apply', res => {
				console.log('面试预约', res)
				store.commit('ADD_NOTICE_MESSAGE', res.data)
			})

			// 好友信息
			this.socket.on('friendMessage', res => {
				store.commit('ADD_FRIEND_MESSAGE', res.data)
				const activeRoom = store.state.activeRoom
				// 如果当前不在聊天页面，设置未读消息
				if (activeRoom !== res.data.friendId && activeRoom !== res.data.userId) {
					store.commit('SET_READ_GATHER', res.data.userId)
				}
			})

			this.socket.on('error', msg => {
				console.log('连接失败', msg)
			})
		}
	}
	
	close() {
		this.socket = null
	}

	getSocket() {
		if (this.socket === null) {
			throw new Error('Socket is not initialized. Call initialize(userId) first.')
		}
		return this.socket
	}
}

export default new SocketManager()